/**
 * 发送get请求
 * @param {string} url     
 * @param {string} params  
 * @param {object} params  
 * @param {object} headers  
 * @param {string} dataType 
 * @returns Promise
 */
 function get(url, params = {}, headers = {}, dataType = 'json'){
    return new Promise((resolve,reject)=>{
        const xhr = new XMLHttpRequest
        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4){
                if(xhr.status === 200){
                    let res = xhr.responseText
                    switch (dataType) {
                        case 'json':
                            res = JSON.parse(res)
                            break;
                    
                        default:
                            break;
                }
                resolve(res)}
                else{
                    reject(xhr.status)
                }
            }
        }
        let tempArr = [] 
        for (let key in params)
        {
            tempArr.push(`${key}=${params[key]}`) 
        }
        xhr.open('get', `${url}?${tempArr.join('&')}`)

        for (let key in headers)
        {
            xhr.setRequestHeader(key, headers[key])
        }

        xhr.send(null)
    })
}


/**
 * 发送post请求
 * @param {string} url     
 * @param {string} params  
 * @param {object} params  
 * @param {object} headers  
 * @param {string} dataType 
 * @returns Promise
 */
 function post(url, params = {}, headers = {}, dataType = 'json'){
    return new Promise((resolve,reject)=>{
        const xhr = new XMLHttpRequest
        xhr.onreadystatechange = function() {
            if(xhr.readyState === 4){
                if(xhr.status === 200){
                    let res = xhr.responseText
                    switch (dataType) {
                        case 'json':
                            res = JSON.parse(res)
                            break;
                    
                        default:
                            break;
                }
                resolve(res)}
                else{
                    reject(xhr.status)
                }
            }
        }
        let tempArr = [] 
        for (let key in params)
        {
            tempArr.push(`${key}=${params[key]}`) 
        }
        xhr.open('post', url)
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')

        for (let key in headers)
        {
            xhr.setRequestHeader(key, headers[key])
        }

        xhr.send(tempArr.join('&'))
    })
}